import React, { Component, PropTypes } from 'react'
import { connect } from "react-redux"
import ReactDOM from 'react-dom'
import AdvanceTable from 'components/advanced-table';
import { Button, Icon, message, Modal, Popconfirm } from "antd";
import constant from "./constant";
import SlideFrame from 'components/slide-frame';
import Info from 'components/info'
import httpFetch from "share/httpFetch";
import { deepFullCopy , messages } from "share/common";

class TemplateContent extends Component {

  state = {
    tableKey: this.props.tableKey
  };

  componentWillMount() {
    const { onRef } = this.props;
    constant.getContext(this);
    onRef && onRef(this);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.tableKey !== this.props.tableKey || nextProps.disabled !== this.props.disabled) {
      this.setState({ tableKey: nextProps.tableKey }, () => {
        ReactDOM.unstable_renderSubtreeIntoContainer(this, this.ele(), document.getElementsByClassName(`target-container-${nextProps.tableKey}`)[0], this.tableRef.onTagReset);
      });
    }
  }

  componentDidMount() {
    ReactDOM.unstable_renderSubtreeIntoContainer(this, this.ele(), document.getElementsByClassName(`target-container-${this.props.tableKey}`)[0])
  }

  ele = () => {
    const { tableKey } = this.state, { operate, disabled = false } = this.props;
    let dataSource = deepFullCopy(constant[tableKey]);
    let columns = dataSource.columns;
    dataSource.deleteUrl && columns.push({
      dataIndex: 'operator', title: messages('common.operation')/*操作*/,
      render: (value, record) => <Popconfirm onConfirm={e => this.handleDelete(e, record)} title={messages('finance-1.key465')/*确定删除嘛*/}><a onClick={(e) => {e.preventDefault();e.stopPropagation();}}>{messages('common.delete')/*删除*/}</a></Popconfirm>
    });
    operate && columns.push(operate);
    let props = {
      columns: columns,
      searchForm: Array.isArray(dataSource.form) ? dataSource.form : dataSource.form(this),
      service: this.service,
      onRef:ref => this.tableRef = ref,
      rowKey: 'id',
      footer: dataSource.footer ? dataSource.footer(this) : [],
      onRow:record => ({onClick: () => dataSource.onRow ? dataSource.onRow(record, this) : this.handleRule(record) })
    };
    dataSource.tableName && (props = Object.assign(props, {
      tableName: dataSource.tableName,
      title: dataSource.title,
      index: true
    }));
    return React.createElement(dataSource.tableName ? AdvanceTable : AdvanceTable.SimpleTable, props, <div>
      {
        dataSource.description && (
          <Info
            dataSource={{ description: dataSource.description }}
            attributes={[{
              title: messages('finance-1.key466')/*设置说明*/, dataIndex: 'description', span: 24, widthFix: false
            }]}
          />
        )
      }
      {
        dataSource.rule && (
          <div style={{ margin: '12px 0px' }}>
            <Button type='primary' onClick={() => this.handleRule({})} disabled={disabled}>{messages('common.create')/*新建*/}</Button>
            { this.handleTag() }
          </div>
        )
      }
    </div>);
  };

  service = (page, size, searchParams) => {
    const { tableKey } = this.state, { tenant, id, language, accountType } = this.props;
    let temp = { page, size, tenantId: tenant.id, ...searchParams, id, accountType };
    if (tableKey === 'Subject') {
      temp.language = language.code;
    }
    return httpFetch.get(constant[tableKey].url, temp)
  };

  handleRule = record => {
    const { tableKey } = this.state, { id, accountType } = this.props;
    let dataSource = constant[tableKey];
    !record.readOnly && SlideFrame.open({
      content: dataSource.rule,
      afterClose: this.afterCloseSlideFrame,
      title: dataSource.title,
      params: { record, id, accountType }
    }, this);
  };

  handleDelete = (e, record) => {
    const { tableKey } = this.state;
    e.stopPropagation();
    let url = constant[tableKey].deleteUrl;
    httpFetch.delete(`${url}=${record[url.split('?')[1]]}`).then(() => {
      message.success(messages('common.operate.success')/*操作成功*/);
      this.tableRef.getList();
    }).catch(e => {
      message.error(e.response.data.message);
    })
  };

  handleTag = () => {
    const { tableKey } = this.state;
    let dataSource = constant[tableKey];
    let res = <a/>;
    switch (dataSource.icon) {
      case 'book':
        res = (
          <a onClick={() => this.handleRule({ onlyRead: true })} style={{ float: 'right', lineHeight: '32px' }}>
            <Icon type="book" />
            {messages('finance-1.key467')/*默认规则*/}
          </a>
        );
        break;
      case 'bulb':
        res = (
          <a onClick={() => Modal.info({
            title: dataSource.moreTitle,
            content: dataSource.moreContent.map(item => <div>{item}</div>)
          })} style={{ float: 'right', lineHeight: '32px' }}>
            <Icon type="bulb" />
            {messages('finance-1.key468')/*了解更多*/}
          </a>
        );
        break;
      default:
        break;
    }
    return res;
  };

  afterCloseSlideFrame = flag => {
    flag && this.tableRef.getList();
  };

  render() {
    const { height } = this.props, { tableKey } = this.state;
    return (
      <div className={`target-container-${tableKey}`} style={{ height: height ? `calc(100vh - ${height}px)` : '100%' }}/>
    )
  }

  static propTypes = {
    tableKey: PropTypes.string
  }

}

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
    language: state.main.language,
    options: state.login.options,
    loginUser: state.login.loginUser
  }
}

TemplateContent.contextTypes = {
  router: PropTypes.object
};

export default connect(mapStateToProps)(TemplateContent)
